from google.appengine.ext import db
import re

class Blockerator(db.Model):
    mute = db.BooleanProperty(default = False)

class UserPrefs(db.Model):
    user = db.UserProperty()
    cs_name = db.StringProperty()
    ci_name = db.StringProperty()
    muter = db.ReferenceProperty(Blockerator)
    created = db.DateTimeProperty(auto_now_add = True)

    def set_user_name(self, name):
        self.cs_name = name
        self.ci_name = name.lower()

    def get_user_name(self):
        return self.cs_name

    def pacify(self):
        muter = self.muter
        muter.mute = True
        muter.put()
        for message in self.message_set:
            message.is_blocked = True
            message.put()

    def block_latest_messages(self, count):
        messages = Message.all().filter('person', self).filter('is_blocked', False).order('-created').fetch(count)
        for message in messages:
            message.is_blocked = True
            message.put()

    @staticmethod
    def person_by_name(nickname):
        return UserPrefs.all().filter('ci_name', nickname.lower()).get()
    
class Message(db.Model):
    text = db.TextProperty()
    is_blocked = db.BooleanProperty(default = False)
    created = db.DateTimeProperty(auto_now_add = True)
    changed = db.DateTimeProperty(auto_now = True)
    
    person = db.ReferenceProperty(UserPrefs)
    
    def set_formatted_text(self, text):
        #remove unwanted chars
        self.text = re.compile('[\n\r\t ]+').sub(' ', text)
        
